<?php ob_start();?>
<html>
<?php
$root = $_SERVER ['DOCUMENT_ROOT'];
include ($root . '/standart/head.php');
include ($root . '/standart/dateHeader.php');
include ($root . '/standart/checkUser.php');
$db = connect ();
?>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Start Bootstrap - SB Admin Version 2.0 Demo</title>
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../font-awesome/css/font-awesome.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../css/jquery.cleditor.css" />
<link href="../css/sb-admin.css" rel="stylesheet">
<link href="../css/tinyBox.css" rel="stylesheet">
<link href="../css/jquery-ui-1.10.4.css" rel="stylesheet"
	type="text/css" media="screen" />
<link href="../css/plugins/dataTables/dataTables.bootstrap.css"
	rel="stylesheet">

<script type="text/javascript" src="../js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="../js/ajax.js"></script>
<script type="text/javascript" src="../js/jquery.plainoverlay.min.js"></script>
<script type="text/javascript">
    var defDate = "<?php echo date('d/m/Y', time());?>";
    function validate(evt, obj) {
		var theEvent = evt || window.event;
	  	var key = theEvent.keyCode || theEvent.which;
	  	key = String.fromCharCode( key );
	  	var regex = /[0-9]/;
	  	if( !regex.test(key) ) {
	    	theEvent.returnValue = false;
	    	if(theEvent.preventDefault) theEvent.preventDefault();
	  	}else{
		  	var time = obj.value+key;
	  		var sMin = '';
			var sHour = '';
			if(time.indexOf(':') > 0){
				sHour = time.split(':')[0];
				sMin = time.split(':')[1];
			}else{
				sHour = time;
			}
			if(sMin != '' && parseInt(sMin) > 59){
				theEvent.returnValue = false;
			}
			if(sHour != '' && parseInt(sHour) > 23){
				theEvent.returnValue = false;
			}
			var retVal = '';
			if(theEvent.returnValue){
				if(sHour.length == 2){
					retVal = sHour+':';
				}else{
					retVal = sHour;
				}
				retVal = retVal + sMin;
				obj.value = retVal;
			}
		  	if(theEvent.preventDefault) theEvent.preventDefault();
	  	}
	}

	function clearForm(){
		$("#orderNo").val('')
		$("#user_id").val('')
		$("#user_name").val('')
		$('#order_pType').val('Ödenmedi')
		$('#shipping_address').val('')
		$('#order_date').val()
		$('#product_note').val('')
		$('#order_time').val('');
		$('#paymentDetail').html('<h2 style="width: 100%; text-align: center;">Kullanıcı Borç / Ödeme Bilgileri</h2>');
		var tbodyElement = $("#orderList");
		while(tbodyElement.find('tr').length > 0){
			$(tbodyElement.find('tr')[0]).remove()
		}
		calcTotalOrderAmount();
		ajx('getInfo.php?type=emptyCart','');
	}
	
	function onLoad(){
		ajx('getInfo.php?type=emptyCart','');
		$('.datepicker').datepicker();
		$('.datepicker').val(defDate);
		$( "#user_name" ).autocomplete({
			source:'getInfo.php?type=name',
			minLength:3,
			select: function( event, ui ) {
				var userId = ui.item.value.split('-')[0].trim();
				var userName = ui.item.value.split('-')[1].trim();
				$("#user_id").val(userId);
				_htm = ajx('getInfo.php?type=address&user_id='+userId,'');
		        $('#shipping_address').html(_htm);
				_htm = ajx('getInfo.php?type=payment&user_id='+userId+'&user_name='+userName,'');
		        $('#paymentDetail').html(_htm);
		        $('#payment_amount').maskMoney({thousands:'', decimal:'.', allowZero:true, suffix: ''});
		        return true;
		      }
		});
		$('#orderListScroll').niceScroll();
	}

	function warningMessage() {
		pane = document.getElementById('invisContentView');
		if(pane.style.height == '0px'){
			pane.style.display = 'block';
			$("#invisContentView").animate({
			    height: "30px"
			}, 1000 );
			setTimeout(function(){warningMessage()}, 5000);
		}else{
			pane.style.display = 'block';
			$("#invisContentView").animate({
			    height: "0px"
			}, 1000 , function() {
				document.getElementById('invisContentView').style.display = 'none';
			});
		}
	}

	function removeOrderToTable(row){
		var menuId = $(row).parent().parent().attr('menu_id');
		$(row).parent().parent().remove();
		calcTotalOrderAmount();
		ajx('getInfo.php?type=removeCart&menu_id='+menuId,'ResultAjx');
	}
	
	function addOrderToTable(btn, operand){
		var menuId = btn.attr('menu_id');
		var menuName = btn.text();
		var price = btn.attr('price');;
		var tbodyElement = $("#orderList");
		var addItem = false;
		for(i = 0; i < tbodyElement.find('tr').length; i++){
			if(tbodyElement.find('tr')[i].getAttribute("menu_id") == menuId){
				if(operand == "+"){
					tbodyElement.find('tr')[i].children[2].children[1].innerText = parseInt(tbodyElement.find('tr')[i].children[2].children[1].innerText)+1;
				}else{
					tbodyElement.find('tr')[i].children[2].children[1].innerText = parseInt(tbodyElement.find('tr')[i].children[2].children[1].innerText)-1;
				}
				tbodyElement.find('tr')[i].children[1].innerText = (parseFloat(tbodyElement.find('tr')[i].children[2].children[1].innerText)*parseFloat(price)).toFixed(2);
				addItem = true;
				break;
			}
		}
		if(!addItem){
			$("#orderList").append(
					"<tr menu_id='"+menuId+"' price='"+price+"'>"+
						"<td>"+menuName+"</td>"+
						"<td>"+price+"</td>"+
						"<td>"+
							"<button type=\"button\" class=\"btn btn-info btn-sm\" style=\"margin-right:5px;\" onclick=\"addOrderToTable($(this).parent().parent(), '-');\"><i class=\"fa fa-minus\"></i></button>"+
							"<span>1</span>"+
							"<button type=\"button\" class=\"btn btn-info btn-sm\" style=\"margin-left:5px;\" onclick=\"addOrderToTable($(this).parent().parent(), '+');\"><i class=\"fa fa-plus\"></i></button>"+
						"</td>"+
						"<td><button type=\"button\" class=\"btn btn-danger btn-sm\" onclick=\"removeOrderToTable(this);\"><i class=\"fa fa-times\"></i></button></td>"+
					"</tr>");
		}
		ajx('getInfo.php?type=addCart&menu_id='+menuId+'&price='+price+'&quantity='+operand+'1','ResultAjx');
		calcTotalOrderAmount();
	}

	function calcTotalOrderAmount(){
		var tbodyElement = $("#orderList");
		totalAmount = 0;
		for(i = 0; i < tbodyElement.find('tr').length; i++){
			totalAmount = totalAmount + parseFloat(tbodyElement.find('tr')[i].children[1].innerText);
		}
		$('#orderTotalAmount').text(totalAmount.toFixed(2));
	}
	
	function ResultAjx(_htm){
		if(_htm.trim().length >= 0){
		}else{
			openNewUnit(ajx('error.php?errorMessage='+_htm, ''));
		}
	}

	function getPaymentFromUser(totalDebt){
		var amount = $('#payment_amount').val();
		if(parseFloat(amount) > parseFloat(totalDebt)){
			openNewUnit(ajx('error.php?errorMessage=Alınan ödeme miktarı kişinin borcundan fazla olamaz.', ''));
		}else{
			url = 'getInfo.php?type=paySth&user_id='+$("#user_id").val();
			url = url + '&amount='+ amount;
			url = url + '&payment='+ $("#payment_type").val();
			loadPageX();
			ajx(url, 'checkPayment');
		}
	}

	function checkPayment(_htm){
		if(_htm.indexOf('success') >= 0){
			openNewUnit(ajx('error.php?success=1&errorMessage=İşleminiz başarıyla tamamlandı.', ''));
			_htm = ajx('getInfo.php?type=payment&user_id='+$("#user_id").val()+'&user_name='+$("#user_name").val(),'');
	        $('#paymentDetail').html(_htm);
	        $('#payment_amount').maskMoney({thousands:'', decimal:'.', allowZero:true, suffix: ''});
		}else{
			openNewUnit(ajx('error.php?errorMessage=Ödeme işlemi sırasında hata oluştu.', ''));
		}
		unloadPageX();
	}

	function openNewUnit(htm) {
		TINY.box.show({html:htm,top:20});
	}

	function completeOrder(){
		if($('#order_time').val() != ''){
			if($("#user_id").val() == '' && $('#order_pType').val() == 'Ödenmedi'){
				openNewUnit(ajx('error.php?errorMessage=Kullanıcılar dışında açık hesap satış yapılamaz.', ''));
				return;
			}
			var url = 'getInfo.php?type=setOrder'
				+'&user_id='+$("#user_id").val()
				+'&order_pType='+$('#order_pType').val()
				+'&shipping_address='+$('#shipping_address').val()
				+'&order_date='+$('#order_date').val()
				+'&product_note='+$('#product_note').val()
				+'&order_time='+$('#order_time').val();
			if($('#orderNo').val() != ''){
				url = url + '&order_id='+$('#orderNo').val();
			}
			loadPageX();
			ajx(url, 'checkError');
		}else{
			openNewUnit(ajx('error.php?errorMessage=Lütfen sipariş saatini belirleyiniz', ''));
		}
	}

	function getOrder(){
		if($('#orderNo').val() == ''){
			clearForm();
			$('#orderCancel').css('display', 'none');
			return;
		}
		loadPageX();
		ajx('getInfo.php?type=orderDetail&orderId='+$('#orderNo').val(), 'placeOrder');
		
	}

	function placeOrder(_htm){
		var data = JSON.parse(_htm);
		if(data == null){
			openNewUnit(ajx('error.php?errorMessage=Sipariş bulunamadı.', ''));
			clearForm();
			unloadPageX();
		}
		$('#user_name').val(data[0].USER_NAME);
		$('#user_id').val(data[0].USER_ID);

		var userId = $('#user_name').val().split('-')[0].trim();
		var userName = $('#user_name').val().split('-')[1].trim();
		_htmx = ajx('getInfo.php?type=address&user_id='+userId,'');
        $('#shipping_address').html(_htmx);
		_htmx = ajx('getInfo.php?type=payment&user_id='+userId+'&user_name='+userName,'');
        $('#paymentDetail').html(_htmx);
        $('#payment_amount').maskMoney({thousands:'', decimal:'.', allowZero:true, suffix: ''});
		
		$('#product_note').val(data[0].NOTES);
		$('#order_date').val(data[0].ORDER_DATE);
		$('#order_time').val(data[0].ORDER_TIME);
		$('#shipping_address').val(data[0].SHIPPING_ADDRESS);
		$('#order_pType').val(data[0].PAYMENT_TYPE);
		$("#orderList").html('');
		for(var index in data[0].DETAIL){
			var detObj = data[0].DETAIL[index];
			var menuName = detObj.PRODUCT_NAME;
			var menuId = detObj.ID;
			var price = parseFloat(detObj.PRICE).toFixed(2);
			var quantity = detObj.QUANTITY;
		    $("#orderList").append(
					"<tr menu_id='"+menuId+"' price='"+price+"'>"+
						"<td>"+menuName+"</td>"+
						"<td>"+price+"</td>"+
						"<td>"+
							"<button type=\"button\" class=\"btn btn-info btn-sm\" style=\"margin-right:5px;\" onclick=\"addOrderToTable($(this).parent().parent(), '-');\"><i class=\"fa fa-minus\"></i></button>"+
							"<span>"+quantity+"</span>"+
							"<button type=\"button\" class=\"btn btn-info btn-sm\" style=\"margin-left:5px;\" onclick=\"addOrderToTable($(this).parent().parent(), '+');\"><i class=\"fa fa-plus\"></i></button>"+
						"</td>"+
						"<td><button type=\"button\" class=\"btn btn-danger btn-sm\" onclick=\"removeOrderToTable(this);\"><i class=\"fa fa-times\"></i></button></td>"+
					"</tr>");
		}
		calcTotalOrderAmount();
		$('#orderCancel').css('display', 'block');
		unloadPageX();
	}

	function cancelOrder(){
		var url = 'getInfo.php?type=cancelOrder'
			+'&orderId='+$('#orderNo').val()
			+'&order_date='+$('#order_date').val()
			+'&order_time='+$('#order_time').val();
		loadPageX();
		ajx(url, 'checkError');
		
	}

	function checkError(_htm){
		if(_htm.indexOf('success') >= 0){
			if(_htm.indexOf('order=') >= 0){
				openNewUnit(ajx('error.php?success=1&errorMessage=Siparişiniz '+ _htm.split('order=')[1] +' numarası ile kaydedildi.', ''));
			}else{
				openNewUnit(ajx('error.php?success=1&errorMessage=İşleminiz başarıyla tamamlandı.', ''));
			}
			clearForm();
		}else{
			openNewUnit(ajx('error.php?errorMessage='+_htm, ''));
		}
		unloadPageX();
	}

	function loadPageX(){
		$('body').plainOverlay('show');
	}

	function unloadPageX(){
		$('body').plainOverlay('hide');
	}
    </script>
</head>

<body onload="onLoad()">
	<div id="wrapper">
		<div id="inner-page-wrapper">
			<div class="row">
				<div class="col-lg-6">
					<div class="panel panel-default">
						<div class="panel-heading">Sipariş Bilgileri</div>
						<div class="panel-body" style="height: 350px">
							<form role="form" method="post" id="orderForm" style="height: 350px">
								<div class="row">
									<div class="col-lg-6">
										<div class="form-group">
											<label>Sipariş No</label> <input class="form-control" name="orderNo" id="orderNo" type="text" onblur="getOrder()">
										</div>
										<div class="form-group">
											<label>Kullanıcı Adı</label> 
											<input class="form-control" name="user_name" id="user_name" type="text"> 
											<input type="hidden" id="user_id" name="user_id">
										</div>
									</div>
									<div class="col-lg-6">
										<div class="form-group">
											<label>Açıklama</label>
											<textarea class="form-control" rows="5" id="product_note" name="product_note"></textarea>
										</div>
									</div>
								</div>
								<div class="row">
									<div class="col-lg-6">
										<div class="form-group">
											<label>Sipariş Tarihi</label> 
											<input type="text" class="form-control datepicker" id="order_date" name="order_date">
										</div>
									</div>
									<div class="col-lg-6">
										<div class="form-group">
											<label>Sipariş Saati</label> 
											<input class="form-control" name="order_time" id="order_time" maxlength="5" type="text" onkeypress="validate(event, this)" placeholder="hh:mm">
										</div>
									</div>
								</div>
								<div class="row">
									<div class="col-lg-6">
										<div class="form-group">
											<label>Teslim Adersi</label> 
											<select class="form-control" name="shipping_address" id="shipping_address">
												<option value="">Masa</option>
											</select>
										</div>
									</div>
									<div class="col-lg-6">
										<div class="form-group">
											<label>Ödeme Tipi</label> 
											<select class="form-control" name="order_pType" id="order_pType">
												<option value="Ödenmedi">Ödenmedi</option>
												<option value="Nakit">Nakit</option>
												<option value="Yemek Kartı">Ticket/SetCart/Multinet</option>
												<option value="Kredi Kartı">Kredi Kartı</option>
											</select>
										</div>
									</div>
								</div>
							</form>
						</div>
						<!-- /.panel-body -->
					</div>
				</div>
				<div class="col-lg-3">
					<div class="panel panel-default">
						<div class="panel-heading">Sipariş Detayı</div>
						<div class="panel-body" style="height: 290px; overflow: hidden;"
							id="orderListScroll">
							<form role="form" method="post" id="orderDetail">
								<div class="table-responsive">
									<table class="table">
										<thead>
											<tr style="text-align: center;">
												<th>Yemek Adı</th>
												<th>Fiyatı</th>
												<th>Adedi</th>
												<th></th>
											</tr>
										</thead>
										<tbody id="orderList">

										</tbody>
									</table>
								</div>
								<!-- /.table-responsive -->
							</form>
						</div>
						<hr style="margin: 0px;" />
						<div class="panel-body" style="height: 60px; overflow: hidden;">
							<label>Toplam Tutar : </label> <span id="orderTotalAmount">0.00</span>TL
							<button type="button" id="orderCancel" class="btn btn-default" onclick="cancelOrder()" style="float: right; display: none; margin-left: 5px;">Sipariş İptal</button>
							<button type="button" id="orderSubmit" class="btn btn-default" onclick="completeOrder()" style="float: right;">Siparişi Bitir</button>
						</div>
						<!-- /.panel-body -->
					</div>
					<!-- /.panel -->
				</div>
				<div class="col-lg-3">
					<div class="panel panel-default">
						<div class="panel-heading">Kullanıcı Ödeme Bilgileri</div>
						<div class="panel-body" style="height: 350px">
							<form role="form" style="height: 350px;" method="post" id="paymentDetail">
								<h2 style="width: 100%; text-align: center;">Kullanıcı Borç / Ödeme Bilgileri</h2>
							</form>
						</div>
						<!-- /.panel-body -->
					</div>
					<!-- /.panel -->
				</div>
			</div>
			<!-- /.row -->
			<div class="row">
				<div class="col-lg-12">
					<div class="panel panel-default">
						<div class="panel-heading">Menü Bilgisi</div>
						<!-- /.panel-heading -->
						<div class="panel-body">
							<!-- Nav tabs -->
							<ul class="nav nav-tabs">
                            	<?php
									$categoryQuery = "SELECT ID, CATEGORY_NAME FROM CATEGORY ORDER BY CATEGORY_ORDER";
									$categoryList = $db->query ( $categoryQuery ) or die ( $categoryQuery . "<br/><br/>" . mysql_error () );
									$i = 1;
									while ( $category = $categoryList->fetch_assoc () ) {
								?>
				                <li class=""><a href="#cat<?php echo $category['ID']?>" data-toggle="tab"><?php echo $category['CATEGORY_NAME']?></a></li>
				                <?php
									}
								?>
                                <li class="active"><a href="#tabldot"
									data-toggle="tab">Tabldot</a></li>
							</ul>
							<!-- Tab panes -->
							<div class="tab-content">
                            	<?php
								$categoryList->data_seek ( 0 );
								while ( $category = $categoryList->fetch_assoc () ) {
									$categoryId = $category ['ID'];
								?>
	                                <div class="tab-pane fade"
									id="cat<?php echo $category['ID'] ?>"> 
	                                
		                                <?php
										$menuQuery = "SELECT * FROM MENU WHERE ID IN (SELECT MENU_ID FROM MENU_FORMAT WHERE CATEGORY_ID = ('$categoryId'))";
										$menuList = $db->query ( $menuQuery ) or die ( $menuQuery . "<br/><br/>" . mysql_error () );
										while ( $menu = $menuList->fetch_assoc () ) {
											$priceQuery = "SELECT * FROM PRICE_LIST WHERE MENU_ID = {$menu['ID']} AND APPLICABLE_FROM<now() ORDER BY APPLICABLE_FROM DESC LIMIT 1";
											$priceResult = $db->query ( $priceQuery ) or die ( $priceQuery . "<br/><br/>" . mysql_error () );
											while ( $priceRecord = $priceResult->fetch_assoc () ) {
												$price = $priceRecord ['PRICE'];
											}
											$priceResult->close ();
											?>
											<button type="button" onclick="addOrderToTable($(this), '+')" class="btn btn-primary btn-lg" menu_id="<?php echo $menu['ID']; ?>" price="<?php echo $price?>"><?php echo $menu['PRODUCT_NAME']?></button>
				                        <?php
										}
										$menuList->close ();
										?>
	                                
	                                </div>
                                <?php
									}
									$categoryList->close ();
								?>
                                <div class="tab-pane active" id="tabldot">
                                	<?php
									$categoryArray = array (
											1 => 'Çorba',
											2 => 'Ara Sıcak',
											3 => 'Ana Yemek',
											4 => 'İkram' 
									);
									$menuQuery = "SELECT PRODUCT_NAME, PICTURE, NOTES, MENU_ID, FIX_MENU.ID AS ID, FIX_MENU.CATEGORY_ID AS CATEGORY
												FROM FIX_MENU, MENU
												WHERE FIX_MENU.MENU_ID = MENU.ID
												AND MENU_DATE = CURRENT_DATE()";
									$menuList = $db->query ( $menuQuery ) or die ( $menuQuery . "<br/><br/>" . mysql_error () );
									$menuCount = 1;
									while ( $menu = $menuList->fetch_assoc () ) {
										$priceQuery = "SELECT * FROM PRICE_LIST WHERE MENU_ID = {$menu['MENU_ID']} AND APPLICABLE_FROM<now() ORDER BY APPLICABLE_FROM DESC LIMIT 1";
										$priceResult = $db->query ( $priceQuery ) or die ( $priceQuery . "<br/><br/>" . mysql_error () );
										while ( $priceRecord = $priceResult->fetch_assoc () ) {
											$price = $priceRecord ['PRICE'];
										}
										$priceResult->close ();
										?>
										<button type="button" onclick="addOrderToTable($(this), '+')" class="btn btn-primary btn-lg" menu_id="<?php echo $menu['ID']; ?>" price="<?php echo $price?>"><?php echo $categoryArray[$menu['CATEGORY']]?> | <?php echo $menu['PRODUCT_NAME']?></button>
				                        <?php
										$menuCount ++;
									}
									$menuList->close ();
									?>
                                </div>
							</div>
						</div>
						<!-- /.panel-body -->
					</div>
					<!-- /.panel -->
				</div>
			</div>
		</div>
		<!-- /#page-wrapper -->
		<div id="invisDiv" style="display: none;"></div>
	</div>
	<!-- /#wrapper -->
	<!-- Page-Level Demo Scripts - Forms - Use for reference -->
</body>
<script type="text/javascript" src="../js/jquery-ui-1.10.4.js"></script>
<script type="text/javascript" src="../js/bootstrap.min.js"></script>
<script type="text/javascript" src="../js/plugins/dataTables/jquery.dataTables.js"></script>
<script type="text/javascript" src="../js/plugins/dataTables/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="../js/plugins/metisMenu/jquery.metisMenu.js"></script>
<script type="text/javascript" src="../js/jquery.maskMoney.min.js"></script>
<script type="text/javascript" src="../js/jquery.nicescroll.min.js"></script>
<script type="text/javascript" src="../js/tinybox.js"></script>
</html>
<?php ob_end_flush(); ?>